package com.jt.sys.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.druid.util.StringUtils;
import com.jt.common.annotation.RequestLog;
import com.jt.common.exception.ServiceException;
import com.jt.common.vo.Node;
import com.jt.sys.dao.SysMenuDao;
import com.jt.sys.dao.SysRoleMenuDao;
import com.jt.sys.entity.SysMenu;
import com.jt.sys.service.SysMenuService;
@Service
@Transactional
public class SysMenuServiceImpl implements SysMenuService {
	@Autowired
	private SysMenuDao sysMenuDao;
	@Autowired
	private SysRoleMenuDao sysRoleMenuDao;
	@Override
	@RequestLog("查看菜单信息")
	public List<Map<String, Object>> findObjects() {
		List<Map<String, Object>> objs = sysMenuDao.findObjects();
		return objs;
	}
	@Override
	@RequestLog("删除菜单信息")
	public int deleteObject(Integer id) {
		if(id==null||id<=0)
			throw new ServiceException("请选择");
		int count=sysMenuDao.getChildCount(id);
		if(count>0)
			throw new ServiceException("请先删除子菜单");
		int rows = sysMenuDao.deleteObject(id);
		if(rows==0)
			throw new ServiceException("次菜单可能已不存在");
		sysRoleMenuDao.deleteObjectsByMenuId(id);
		return rows;
	}
	@Override
	public List<Node> findZtreeMenuNodes() {
		List<Node> list = sysMenuDao.findZtreeMenuNodes();
		return list;
	}
	@Override
	@RequestLog("添加菜单信息")
	public int saveObject(SysMenu entity) {
		if(entity==null)
			throw new ServiceException("保存对象不能为空");
		if(StringUtils.isEmpty(entity.getName()))
			throw new ServiceException("保存对象的名字不能为空");
		Date date=new Date();
		entity.setCreatedTime(date);
		entity.setModifiedTime(date);
		entity.setCreatedUser("admin");
		entity.setModifiedUser("admin");
		int rows=0;
		try {
			rows = sysMenuDao.insertObject(entity);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("保存失败");
		}
		return rows;
	}
	@Override
	public Map<String, Object> findObjectById(Integer id) {
		if(id==null||id<=0)
			throw new IllegalArgumentException("数据不合法,id="+id);
		Map<String, Object> map = sysMenuDao.findObjectById(id);
		if(map==null||map.size()==0)
			throw new ServiceException("此记录并不存在");
		return map;
	}
	@Override
	@RequestLog("修改菜单信息")
	public int updateObject(SysMenu entity) {
		if(entity==null)
			throw new ServiceException("保存对象不能为空");
		if(StringUtils.isEmpty(entity.getName()))
			throw new ServiceException("保存对象的名称不能为空");
		Date date=new Date();
		entity.setCreatedTime(date);
		entity.setModifiedTime(date);
		entity.setCreatedUser("admin");
		entity.setModifiedUser("admin");
		int rows;
		try {
			rows = sysMenuDao.updateObject(entity);
		} catch (Throwable e) {
			e.printStackTrace();
			throw new ServiceException("更新失败");
		}
		return rows;
	}

}
